package com.cms.model;

import java.util.List;

import com.cms.common.kit.StrKit;
import com.cms.plugin.db.Model;
import com.cms.plugin.db.Page;
import com.cms.plugin.db.annotation.Table;

@Table("s_role")
public class Role extends Model<Role>{

	/**
	 * 
	 */
	private static final long serialVersionUID = -2027821698841422706L;
	public static final Role dao = new Role();
	
	/**
	 * 所有 sql 写在 Model 或 Service 中，不要写在 Controller 中，养成好习惯，有利于大型项目的开发与维护
	 */
	public Page<Role> paginate(int pageNumber, int pageSize) {
		return paginate(pageNumber, pageSize, "select *", "from s_role order by id");
	}

	public boolean deleteRoleByAid(String aid) {
		return update("delete from s_role_admin where admin_id=?", aid);
	}

	public boolean grant(String roleId, String rids) {
		update("delete from s_res_role where role_id=?", roleId);
		if(StrKit.isBlank(rids))return true;
		Object [][]batch_insert_array=buildInsertArray(rids,roleId);
		int[] batchInsert = batchInsert("insert into s_res_role(res_id,role_id) values(?,?)", batch_insert_array);
		if(batchInsert.length>0){
			return true;
		}
		return false;
	}

	private Object[][] buildInsertArray(String rids, String roleId) {
		String[] split = rids.split(",");
		Object[][] batch=new Object[split.length][2];
		for (int i = 0; i < split.length; i++) {
			batch[i][0]=split[i];
			batch[i][1]=roleId;
		}
		return batch;
	}

	public List<Role> getAllRoles() {
		return find("select * from s_role");
	}
}
